package com.bjpowernode.config.handler;

import com.bjpowernode.result.R;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 * Advice : spring aop的通知
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        e.printStackTrace();
        return R.FAIL(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        // 获取绑定的结果
        BindingResult bindingResult = e.getBindingResult();
        // 获取所有错误
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            stringBuilder.append(field + ":" + defaultMessage + ",");
        }
        // 遍历
        return R.FAIL(stringBuilder.toString());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public R handleException(DataIntegrityViolationException e) {
        e.printStackTrace();
        return R.FAIL("数据操作失败 , 可能存在外键约束");
    }
}
